package fun.tan90.easy.binlog.plugin.webhook.listener;


import cn.hutool.core.codec.Base64;
import com.dtflys.forest.Forest;
import com.dtflys.forest.http.ForestRequest;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputResEnum;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEvent;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEventRes;
import fun.tan90.easy.binlog.plugin.common.listener.BinlogEventPluginListener;
import fun.tan90.easy.binlog.plugin.common.model.BinlogData;
import fun.tan90.easy.binlog.plugin.common.model.BinlogOutputRule;
import fun.tan90.easy.binlog.plugin.webhook.model.WebhookParams;
import lombok.extern.slf4j.Slf4j;
import org.noear.dami.Dami;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * description 应用初始化后置处理器，防止 spring 事件被多次执行
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/8/17 8:31
 */
@Slf4j
public class WebhookEventProcessor implements BinlogEventPluginListener, ApplicationListener<ApplicationReadyEvent> {

    private final AtomicBoolean initialized = new AtomicBoolean(false);

    private final LoadingCache<String, WebhookParams> webhookParamsCache;

    public WebhookEventProcessor(LoadingCache<String, WebhookParams> webhookParamsCache) {
        this.webhookParamsCache = webhookParamsCache;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (initialized.compareAndSet(false, true)) {
            Dami.<BinlogDataEvent, BinlogDataEventRes>bus().listen(DamiEventConstants.BINLOG_EVENT_TOPIC + outputType(), payload -> {
                BinlogDataEvent binlogDataEvent = payload.getContent();
                String masterCode = binlogDataEvent.getMasterCode();
                List<BinlogData> binlogDataList = binlogDataEvent.getBinlogDataList();
                List<BinlogOutputRule> binlogOutputTypeRules = binlogDataEvent.getBinlogOutputRules();
                for (BinlogOutputRule binlogOutputRule : binlogOutputTypeRules) {
                    String outputRuleCountId = binlogOutputRule.getOutputRuleCountId();
                    String outputCode = binlogOutputRule.getOutputCode();
                    WebhookParams webhookParams = webhookParamsCache.get(outputCode);
                    if (webhookParams != null) {
                        ForestRequest<?> forestRequest = Forest.post(webhookParams.getUrl())
                                .contentTypeJson()
                                .setBackend("okhttp3")
                                .maxRetryCount(webhookParams.getMaxRetryCount())
                                .setConnectTimeout(webhookParams.getConnectTimeout() * 1000)
                                .setReadTimeout(webhookParams.getReadTimeout() * 1000)
                                .onRetry((req, res) -> {
                                    log.info("onRetry");
                                })
                                .onSuccess((data, req, res) -> {
                                    log.info("onSuccess");
                                    reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                })
                                .onError((ex, req, res) -> {
                                    log.info("onError");
                                    reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                })
                                .addQuery("masterCode", masterCode);
                        String authType = webhookParams.getAuthType();
                        if ("1".equals(authType)) {
                            WebhookParams.BasicAuth basicAuth = webhookParams.getBasicAuth();
                            forestRequest.addHeader("Authorization", "Basic " + Base64.encode(basicAuth.getUsername() + ":" + basicAuth.getPassword()));
                        }
                        for (BinlogData binlogData : binlogDataList) {
                            if (filterOutput(binlogOutputRule, binlogData)) {
                                forestRequest.addBody(binlogData).execute();
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public String outputType() {
        return OutputTypeEnum.WEBHOOK.getOutput();
    }
}
